package com.common.message.service;
import com.common.core.constants.CacheConstants;
import com.common.core.utils.CodeGeneratorUtil;
import com.common.redis.service.RedisService;
import jakarta.annotation.Resource;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.common.core.constants.Constants.KEY_PREFIX;

@Slf4j
@Component
public class MailService {

    @Value("${spring.mail.username}")
    private String hostMail;

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private RedisService redisService;

    public boolean sendMail(String email) {
        try {
            String redisKey = CacheConstants.EMAIL_CODE_KEY + email;
        
            // 检查发送频率（60秒内不重复发送）
            Long ttl = redisService.getExpire(redisKey, TimeUnit.SECONDS);
            if (ttl != null && ttl > 0) {
                log.info("验证码未过期，不重复发送，email:{}, 剩余TTL:{}秒", email, ttl);
                return true;
            }

            // 生成6位验证码
            String code = CodeGeneratorUtil.generateCode(6);

            // 写入Redis，有效期60秒
            redisService.setCacheObject(redisKey, code, 60L, TimeUnit.SECONDS);

            // 构造邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name());

            helper.setTo(email);
            helper.setFrom(new InternetAddress(hostMail, "OJ系统", StandardCharsets.UTF_8.name()));
            helper.setSubject("OJ系统登录验证码");
            helper.setText(
                    "<p style='color:black;font-size:14px;'>您正在登录 <b>在线OJ系统</b>，验证码为：<b>"
                            + code + "</b><br/>有效期 60 秒，请尽快使用。</p>",
                    true
            );

            // 发送
            mailSender.send(message);
            log.info("验证码发送成功，email:{}", email);
            return true;
        } catch (Exception e) {
            log.error("邮件发送失败，email:{}，原因：{}", email, e.getMessage(), e);
            return false;
        }
    }

    public boolean verifyCode(String email, String inputCode) {
        String redisKey = CacheConstants.EMAIL_CODE_KEY + email;

        // 从 Redis 中取出缓存的验证码
        String cached = redisService.getCacheObject(redisKey, String.class);

        boolean ok = Objects.equals(cached, inputCode);
        if (ok) {
            // 验证通过后删除，避免重复使用
            redisService.deleteObject(redisKey);
        }
        return ok;
    }
}
